class AjaxController < ApplicationController
  include HomeHelper
  include UserHelper

  skip_before_filter :verify_authenticity_token


  def edit_post
  	begin
		@edit_post = Post.find(params[:id])
		if !params[:content].nil?
			@edit_post.update_attributes(:content => params[:content])
		end
	  	respond_to do |format|
		  format.json { render :json => @edit_post }
		end
  	rescue Exception => e
  		@edit_post = Post.new
	  	respond_to do |format|
		  format.json { render :json => @edit_post }
		end
  	end
  end

  def add_comment
  	begin
  		if !params[:id].nil? && !params[:content].nil?
  			data = { 'post_id' => params[:id], 
  					 'user_id' => @user[:user_id],
  					 'content' => params[:content]
  			}
  			@comment = Comment.new(data)
        @comment.save
        returnData = { 'time'    => change_date(Time.now),
                        'result' => 'Success !',
                        'c_id'   => @comment[:comment_id],
                        'del_path' => del_comment_path
        }
  			respond_to do |format|
  				format.json { render :json => returnData }
  			end  			
  		else
        returnData = { 'time' => change_date(Time.now),
                        'result' => 'Invalid information !'
        }        
  			respond_to do |format|
  				format.json { render :json => returnData }
  			end  			
  		end

  	rescue Exception => e
      # writelog
      logger.debug("********** Bugs **********\n#{e.inspect}\n********** End Bugs **********")
      
      returnData = { 'time' => change_date(Time.now),
                      'result' => 'Failed to add comment !'
      } 
  		respond_to do |format|
  			format.json { render :json => returnData }
  		end
  	end
  end

  def del_comment
    begin
      if !params[:pid].nil? && !params[:cid].nil?
        @comment = Comment.where(["user_id = ? AND post_id = ? AND comment_id = ?", @user[:user_id], params[:pid], params[:cid]]).first
        if @comment.nil?
          returnData = { 'result' => 'Invalid information !'}
          respond_to do |format|
            format.json { render :json => returnData }
          end 
        else
          @comment.destroy
          returnData = { 'result' => 'Success !'}
          respond_to do |format|
            format.json { render :json => returnData }
          end                   
        end        
      else
        returnData = { 'result' => 'Invalid information !' }        
        respond_to do |format|
          format.json { render :json => returnData }
        end  
      end
    rescue Exception => e
      # writelog
      logger.debug("********** Bugs **********\n#{e.inspect}\n********** End Bugs **********")
      
      returnData = { 'result' => 'Failed to del comment !' } 
      respond_to do |format|
        format.json { render :json => returnData }
      end    
    end
  end

  def load_post
    begin
      user_id = 0
      page = 0;
      style = '';
      if !params[:id].nil?
        user_id = params[:id]
      elsif !params[:style].nil? && params[:style] == "user"
        user_id = @user[:user_id]
      else
        user_id = -1
      end

      if !params[:page].nil?
        page = params[:page].to_i
      end

      if !params[:style].nil?
        style = params[:style]
      end      

      if user_id == 0 || page == 0 || style == ''
       returnData = { 'result' => 'Invalid information !' }        
        respond_to do |format|
          format.json { render :json => returnData }
        end
      else
        if style == 'user'
          @all_post = Post.all(:conditions => ["user_id = ?", user_id], :order => "created_at DESC", :limit => 5, :offset => (page - 1)*5 )
        elsif style == 'home'
          @all_post = Post.all(:order => "created_at DESC", :limit => 5, :offset => (page - 1)*5)
        end
        postData = []
        if @all_post.size > 0
          @all_post.each do |post|
            temp = {}
            listComments = []
            if post.comment.size > 0              
              post.comment.each do |comment|
                tempComment = {}
                cmAvatar = show_avatar(comment.user.avatar)
                if cmAvatar == '#'
                  cmAvatar = '/data/no-image.jpg'
                end

                allowDelete = 0
                if !@user.nil? && @user.user_id == comment.user.user_id
                  allowDelete = 1
                end
                tempComment = {
                  'comment_id'   => comment.comment_id,
                  'content'      => comment.content,
                  'user_id'      => comment.user_id,
                  'time'         => change_date(comment.created_at),
                  'deletePath'   => del_comment_path,
                  'user_avatar'  => cmAvatar,
                  'user_username'=> comment.user.username,
                  'allowDelete'  => allowDelete,
                  'del_path'     => del_comment_path,
                  'user_path'    => another_user_path(comment.user_id) 
                }
                listComments.push(tempComment)
              end
            end

            avatar = show_avatar(post.user.avatar)
            if avatar == '#'
              avatar = '/data/no-image.jpg'
            end

            if !@user.nil? 
              box_comment = set_comment @user.avatar, @user.username, @user.user_id, post.post_id, 2
            else
              box_comment = set_comment '', '', '', post.post_id, 2
            end

            temp = {
              'post_id'       => post.post_id,
              'post_content'  => post.content,
              'post_date'     => show_date(post.created_at, post.updated_at, post.post_id, 2),
              'user_owner'    => this_owner?(post.user.username, post.post_id, 2),
              'user_avatar'   => avatar,
              'user_username' => post.user.username,
              'comments'      => listComments,
              'box_comment'   => box_comment,
              'user_id'       => post.user_id,
              'user_path'     => another_user_path(post.user_id) 
            }
            postData.push(temp)
          end
        end

        returnData = { 'result' => 'Success !',
                        'data'  => postData,
                        'endPoint' => @all_post.size == 5?false:true
                    }
        respond_to do |format|
          format.json { render :json => returnData }
        end        
      end


    rescue Exception => e
      # writelog
      logger.debug("********** Bugs **********\n#{e.inspect}\n#{e.backtrace}\n********** End Bugs **********")
      
      returnData = { 'result' => 'Failed to load post !' } 
      respond_to do |format|
        format.json { render :json => returnData }
      end       
    end
  end
end
